﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace DeHeng_Mes.Utils
{
    public class CsvReaderHelper
    {
        public static async Task<Dictionary<string, string[]>> ReadCsv(string filePath, string alignHeader)
        {
            // 创建一个字典，存储列标题和列数据
            var csvData = new Dictionary<string, List<string>>();

            // 打开 CSV 文件并读取
            using (var reader = new StreamReader(filePath,Encoding.Default))
            {
                // 异步读取标题行
                string headerLine = await reader.ReadLineAsync();
                var headers = ParseCsvLine(headerLine);

                // 初始化列集合
                foreach (var header in headers)
                {
                    csvData[header] = new List<string>();
                }

                // 异步逐行读取
                while (!reader.EndOfStream)
                {
                    string line = await reader.ReadLineAsync();
                    var values = ParseCsvLine(line);

                    // 处理列数据
                    for (int i = 0; i < headers.Length; i++)
                    {
                        if (i < values.Length && csvData.ContainsKey(headers[i]))
                        {
                            csvData[headers[i]].Add(values[i]);
                        }
                    }
                }
            }

            // 将字典中的每个 List<string> 转换成 string[] 数组
            var result = new Dictionary<string, string[]>();

            // 确保每列的长度一致
            int maxRows = csvData[alignHeader].Count;  // 获取 alignHeader 列的行数

            foreach (var kvp in csvData)
            {
                // 对每列进行填充，确保长度一致
                var columnValues = kvp.Value;
                while (columnValues.Count < maxRows)
                {
                    columnValues.Add(""); // 如果当前列行数小于最大行数，填充 null
                }

                result[kvp.Key] = columnValues.ToArray();
            }

            return result;
        }

        private static string[] ParseCsvLine(string line)
        {
            // 处理带引号和逗号的字段
            List<string> fields = new List<string>();
            StringBuilder currentField = new StringBuilder();
            bool inQuotes = false;

            for (int i = 0; i < line.Length; i++)
            {
                char c = line[i];

                if (c == '"')
                {
                    // 处理转义引号 ("")
                    if (inQuotes && i < line.Length - 1 && line[i + 1] == '"')
                    {
                        currentField.Append('"');
                        i++; // 跳过下一个引号
                    }
                    else
                    {
                        inQuotes = !inQuotes;
                    }
                }
                else if (c == ',' && !inQuotes)
                {
                    fields.Add(currentField.ToString());
                    currentField.Clear();
                }
                else
                {
                    currentField.Append(c);
                }
            }

            // 添加最后一个字段
            fields.Add(currentField.ToString());
            return fields.ToArray();
        }

    }
}
